import allure
import requests

from src.log import log
from src.validate import Assert
from src.extract import Extract
from src.config_util import Config

requests.packages.urllib3.disable_warnings()


class HttpSession(requests.Session):

    def __init__(self):
        super(HttpSession, self).__init__()
        self.env = Config("conf/env.yml").get_conf(Config().get_conf("env"))
        self.update_headers({
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"
        })

    def send_request(self, params):
        request_obj = params.get("request")
        with allure.step("步骤二: 发送请求"):
            response = self.request(**request_obj, verify=False)
            with allure.step(f"请求路径: {request_obj.get('url')}"):
                log.info(f"请求路径: {request_obj.get('url')}")
            with allure.step(f"请求方式: {request_obj.get('method')}"):
                log.info(f"请求方式: {request_obj.get('method')}")
            with allure.step(f"请求头: {self.headers}"):
                log.info(f"请求头: {self.headers}")
            if request_obj.get('params'):
                with allure.step(f"请求参数params: {request_obj.get('params')}"):
                    log.info(f"请求参数params: {request_obj.get('params')}")
            if request_obj.get('data'):
                with allure.step(f"请求参数data: {request_obj.get('data')}"):
                    log.info(f"请求参数data: {request_obj.get('data')}")
            if request_obj.get('json'):
                with allure.step(f"请求参数json: {request_obj.get('json')}"):
                    log.info(f"请求参数json: {request_obj.get('json')}")
            if request_obj.get('files'):
                with allure.step(f"请求参数 files: {request_obj.get('files')}"):
                    log.info(f"请求参数 files: {request_obj.get('files')}")
            with allure.step(f"响应状态码: {response.status_code}"):
                log.info(f"响应状态码: {response.status_code}")
            with allure.step(f"响应头: {response.headers}"):
                log.info(f"响应头: {response.headers}")
            with allure.step(f"响应内容: {response.json()}"):
                log.info(f"响应内容: {response.json()}")
        # 断言
        assert_result = False
        with allure.step("步骤三: 响应断言"):
            if Assert(response, params.get("validate")).valid():
                assert_result = True
        # 提取变量
        if assert_result and params.get("extract"):
            with allure.step("步骤四: 保存变量"):
                Extract(response, params.get("extract")).extract()
        return response

    def _send(self, *args, **kwargs):
        return self.request(*args, **kwargs, verify=False)

    def update_headers(self, headers):
        self.headers.update(headers)

    def update_cookies(self, cookies):
        self.cookies.update(cookies)
